/**
 * Copyright (C) 2009-2012, KingHool.com
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses.
 */
package com.kinghool.smodel.rule;

import java.util.ArrayList;
import java.util.List;

import com.kinghool.ebos.commons.utils.Assert;
import com.kinghool.ebos.commons.utils.Utils;
import com.kinghool.smodel.IModel;
import com.kinghool.smodel.ITreeModel;

/**
 * 
 * @Author Allen Deng(dengtailin@gmail.com) 
 */
public class PropertyMandantoryRule extends BaseModelRule implements IModelRule {
    private List<String> mandantoryAttrs = new ArrayList<String>();
    private String childFullName;
    
	public PropertyMandantoryRule(int severity, String[] attributes) {
		this(severity, null, attributes);
	} 
	
	public PropertyMandantoryRule(int severity, String childFullName, String[] attributes) {
		super(severity);
		if (! Assert.isNullOrEmpty(attributes)) {
			for (String attribute : attributes) {
				mandantoryAttrs.add(attribute);
			}
		}
		this.childFullName = childFullName;
	} 
	
	public List<String> validate(IModel model) {
		List<String> errorMessages = Utils.newList();
		if (Assert.isNotNullNotEmpty(childFullName)) {
			if (model instanceof ITreeModel) {
				ITreeModel treeModel = (ITreeModel) model;
				List<ITreeModel> childrenModel = treeModel.getTreeChild(childFullName);
				for (ITreeModel childModel : childrenModel.toArray(new ITreeModel[0])) {
					List<String> childValidateMsgs = validateModel(childModel);
					if (!Assert.isNullOrEmpty(childValidateMsgs)) {
						errorMessages.addAll(childValidateMsgs);
					}
				}
			}
		} else {
			errorMessages.addAll(validateModel(model));
		}
		return errorMessages;
	}
	
	private List<String> validateModel(IModel model) {
		List<String> errorMessages = Utils.newList();
		for (String attr : mandantoryAttrs) { 
			if (Assert.isNullOrEmpty(model.getStringProperty(attr))){
				errorMessages.add("Bad format for the model:" +
				       "The property '" + attr + "' " + " of the model ["+ model.toString() + "] is mandantory."); 
			}
	    } 
		return errorMessages;
	}
	
	public boolean isMandatory(String property) {
		if (Assert.isNotNullNotEmpty(property)) {
			return mandantoryAttrs.contains(property);
		}
		return false;
	}
}
